package com.itjin.controller;

import com.itjin.model.domain.dto.SendMessageDTO;
import com.itjin.model.domain.entity.User;
import com.itjin.model.domain.vo.MessageVO;
import com.itjin.model.result.Result;
import com.itjin.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/message")
@Tag(name = "消息控制器")
@Slf4j
public class MessageController {

  @Resource
  private MessageService messageService;

  /**
   * 发送消息
   */
  @PostMapping("/send")
  @Operation(summary = "发送消息")
  public Result<MessageVO> sendMessage(@RequestBody SendMessageDTO messageDTO) {
    try {
      // 基本参数校验
      if (messageDTO.getReceiverId() == null) {
        return Result.failure(400, "接收者ID不能为空");
      }
      if (messageDTO.getContent() == null || messageDTO.getContent().trim().isEmpty()) {
        return Result.failure(400, "消息内容不能为空");
      }
      if (messageDTO.getSenderId() == null) {
        return Result.failure(400, "发送者ID不能为空");
      }
      if (messageDTO.getSenderId().equals(messageDTO.getReceiverId())) {
        return Result.failure(400, "不能给自己发送消息");
      }

      // 发送消息
      MessageVO messageVO = messageService.sendMessage(messageDTO.getSenderId(), messageDTO);
      return Result.success(messageVO);
    } catch (IllegalArgumentException e) {
      log.error("发送消息参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("发送消息失败", e);
      return Result.failure(500, "发送消息失败: " + e.getMessage());
    }
  }

  /**
   * 获取用户的消息列表
   * 
   * @param userId       用户ID
   * @param targetUserId 可选参数，如果提供则获取与该用户的对话记录
   */
  @GetMapping("/list")
  @Operation(summary = "获取用户的消息列表")
  public Result<List<MessageVO>> getUserMessages(@RequestParam Integer userId,
      @RequestParam(required = false) Integer targetUserId) {
    try {
      List<MessageVO> messages;
      if (targetUserId != null) {
        messages = messageService.getConversationMessages(userId, targetUserId);
      } else {
        messages = messageService.getUserMessages(userId);
      }
      return Result.success(messages);
    } catch (Exception e) {
      log.error("获取消息列表失败: {}", e.getMessage());
      return Result.failure(500, "获取消息列表失败: " + e.getMessage());
    }
  }

  /**
   * 标记消息为已读
   */
  @PutMapping("/read/{messageId}")
  @Operation(summary = "标记消息为已读")
  public Result<Boolean> markMessageAsRead(@PathVariable Long messageId, @RequestParam Integer userId) {
    try {
      boolean success = messageService.markMessageAsRead(messageId, userId);
      return success ? Result.success(true) : Result.failure(400, "标记消息已读失败");
    } catch (Exception e) {
      log.error("标记消息已读失败: {}", e.getMessage());
      return Result.failure(500, "标记消息已读失败: " + e.getMessage());
    }
  }

  /**
   * 查询用户帖子的赞与收藏情况
   * 
   * @param userId 用户ID
   * @param days   查询最近几天的数据，默认为7天
   * @param page   页码，默认为1
   * @param size   每页条数，默认为10
   */
  @GetMapping("/interactions")
  @Operation(summary = "查询用户帖子的赞与收藏情况")
  public Result<Map<String, Object>> getPostInteractions(
      @RequestParam @Parameter(description = "用户ID") Integer userId,
      @RequestParam(required = false) @Parameter(description = "查询最近几天的数据") String days,
      @RequestParam(required = false, defaultValue = "1") @Parameter(description = "页码") Integer page,
      @RequestParam(required = false, defaultValue = "10") @Parameter(description = "每页条数") Integer size) {
    try {
      if (userId == null || userId <= 0) {
        return Result.failure(400, "用户ID不合法");
      }

      // 处理days参数
      Integer daysValue = null;
      if (days != null && !days.equals("null")) {
        try {
          daysValue = Integer.parseInt(days);
        } catch (NumberFormatException e) {
          // 如果解析失败，保持为null
        }
      }

      Map<String, Object> interactions = messageService.getPostInteractions(userId, daysValue, page, size);
      return Result.success(interactions);
    } catch (Exception e) {
      log.error("获取帖子互动信息失败: {}", e.getMessage());
      return Result.failure(500, "获取帖子互动信息失败: " + e.getMessage());
    }
  }

  /**
   * 查看用户近期的新增关注情况
   * 
   * @param userId 用户ID
   * @param days   查询最近几天的数据，默认为7天
   * @param page   页码，默认为1
   * @param size   每页条数，默认为10
   */
  @GetMapping("/new-followers")
  @Operation(summary = "查看用户近期的新增关注情况")
  public Result<Map<String, Object>> getRecentFollowers(
      @RequestParam @Parameter(description = "用户ID") Integer userId,
      @RequestParam(required = false) @Parameter(description = "查询最近几天的数据") String days,
      @RequestParam(required = false, defaultValue = "1") @Parameter(description = "页码") Integer page,
      @RequestParam(required = false, defaultValue = "10") @Parameter(description = "每页条数") Integer size) {
    try {
      if (userId == null || userId <= 0) {
        return Result.failure(400, "用户ID不合法");
      }

      // 处理days参数
      Integer daysValue = null;
      if (days != null && !days.equals("null")) {
        try {
          daysValue = Integer.parseInt(days);
        } catch (NumberFormatException e) {
          // 如果解析失败，保持为null
        }
      }

      Map<String, Object> followers = messageService.getRecentFollowers(userId, daysValue, page, size);
      return Result.success(followers);
    } catch (Exception e) {
      log.error("获取近期关注信息失败: {}", e.getMessage());
      return Result.failure(500, "获取近期关注信息失败: " + e.getMessage());
    }
  }

  /**
   * 查看用户最近帖子相关的评论情况
   * 
   * @param userId 用户ID
   * @param days   查询最近几天的数据，默认为7天
   * @param page   页码，默认为1
   * @param size   每页条数，默认为10
   */
  @GetMapping("/recent-comments")
  @Operation(summary = "查看用户最近帖子相关的评论情况")
  public Result<Map<String, Object>> getRecentComments(
      @RequestParam @Parameter(description = "用户ID") Integer userId,
      @RequestParam(required = false) @Parameter(description = "查询最近几天的数据") String days,
      @RequestParam(required = false, defaultValue = "1") @Parameter(description = "页码") Integer page,
      @RequestParam(required = false, defaultValue = "10") @Parameter(description = "每页条数") Integer size) {
    try {
      if (userId == null || userId <= 0) {
        return Result.failure(400, "用户ID不合法");
      }

      // 处理days参数
      Integer daysValue = null;
      if (days != null && !days.equals("null")) {
        try {
          daysValue = Integer.parseInt(days);
        } catch (NumberFormatException e) {
          // 如果解析失败，保持为null
        }
      }

      Map<String, Object> comments = messageService.getRecentComments(userId, daysValue, page, size);
      return Result.success(comments);
    } catch (Exception e) {
      log.error("获取近期评论信息失败: {}", e.getMessage());
      return Result.failure(500, "获取近期评论信息失败: " + e.getMessage());
    }
  }
}
